<?php
global $db;
require_once "../../tool/sql.php";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
if(isset($_POST["data"])) {
    $data = json_decode($_POST["data"],true);
    $result = "0";
    $res = $db->selectById("userinfo","learned_word_count","name",$_SESSION['user']);
    if($res == null)
        die($db->getStmtError());
    $learned_count = 0;
    foreach ($res as $r) {
        $learned_count = $r['learned_word_count'];
    }
    $res = $db->selectById("userinfo", "public_cache", "name", $_SESSION['user']);
    if ($res == null)
        die($db->getStmtError());
    $public_cache = "";
    foreach ($res as $r) {
        $public_cache = $r['public_cache'];
    }
    $public_cache = json_decode($public_cache,true);
    $public_delete = json_decode($_POST["public_delete"],true);
    foreach ($public_delete as $del) {
        $search = array_search($del,$public_cache);
        if ($search !== false) {
            unset($public_cache[$search]);
        }
    }
    $public_cache = array_values($public_cache);
    if(!$db->update("userinfo","name='".$_SESSION['user']."'",["public_cache"=>json_encode($public_cache)]))
        die($db->getStmtError());
    $learned_count -= $_POST["deleteCount"];
    if(!$db->update("userinfo","name='".$_SESSION['user']."'",["learned_word_count"=>$learned_count]))
        die($db->getStmtError());
    for($i = 0;$i<count($data);$i++) {
        $where = "`list_id` = $i and `owner_name` = '".$_SESSION['user']."'";
        if (!$db->update("wordlist", $where, ["text" => json_encode($data[$i])])) {
            $result = $db->getStmtError();
        }
        //更人性化的用户引导
        //词库的加入
        //txt文件方式导入词库
    }
    echo $result;
} else {
    $res = $db->select("wordlist", "text", "`owner_name` = '" . $_SESSION['user'] . "'");
    $arr = [];
    foreach ($res as $list) {
        $arr[] = $list['text'];
    }
    echo json_encode($arr);
}
